package com.quantstack.llcommonlibrary.base;

import android.app.Application;
import android.content.Context;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @author wu_ming_zhi_bei
 * @date 2021/1/26 14:09
 * @Notes
 */
public abstract class BaseViewModel<T extends BaseHttpResult> extends AndroidViewModel {
    private T model;
    //在请求过程中，UI层destroy了怎么办，不及时取消订阅，可能会造成内存泄漏。
    // CompositeDisposable就上场了，它可以对我们订阅的请求进行统一管理。
    private CompositeDisposable compositeDisposable;
    protected Context mContext;
    public BaseView baseView;

    public void setBaseView(BaseView baseView) {
        this.baseView = baseView;
    }

    public BaseViewModel(@NonNull Application application) {
        super(application);
        this.mContext = application;
    }

    public void addDisposable(Observable<?> observable, BaseObserver observer) {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable.add(observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(observer));
    }

    public void removeDisposable() {
        if (compositeDisposable != null) {
            compositeDisposable.dispose();
        }
    }

    public OnPageDataListener onPageDataListener;
    public void setOnPageDataListener(OnPageDataListener onPageDataListener){
        this.onPageDataListener = onPageDataListener;
    }
    public interface OnPageDataListener{
        void onSuccess(String tag);
        void onError(String tag,String msg);
    }
}
